import React, { useEffect, useState } from "react";
import { Card, Button, message } from "antd";
import { useNavigate } from "react-router-dom";
import { Hexagon, Kcarousel, SegmentedList, RightClickMenu } from "../../componts/componts.tsx";
import leftInco from "../../img/leftInco.svg";
import dbTitleInco from "../../img/dbTitleInco.svg";
import TaskItem from "./TaskItem.tsx";
// import { GetTodoList } from "../../api/otherSystem.ts";
// import { dbTest } from "../../api/otherSystem.ts";
// 待办卡片
const TaskList: React.FC = () => {
  const navigate = useNavigate();

  // 存储数据
  const [listData, setListData] = useState<any[]>([]);
  const [filteredData, setFilteredData] = useState<any[]>([]);
  const [sizeType, setsizeType] = useState<{ hights: string; pageSize: number }>({ hights: "436px", pageSize: 10 });
  useEffect(() => {
    const fetchData = async () => {
      // 模拟数据
      const response = await new Promise<any[]>(resolve =>
        setTimeout(
          () =>
            resolve([
              {
                // 任务ID
                taskId: "1709192275122",
                // 流程名称
                flowName: "集团年度预算（一上）",
                // 任务状态
                taskStatus: "pending",
                // 任务生成时间
                opTime: timer("2024-02-29 15:37:55"),
                // 其他
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                // 自主添加
                status: { color: "#7FCFD8", text: "税" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                taskStatus: "pending",
                opTime: timer("2024-02-29 15:37:55"),
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#AC92ED", text: "险" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#7FCFD8", text: "税" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                taskStatus: "pending",
                opTime: timer("2024-02-29 15:37:55"),
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#0363B0FF", text: "股" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#9ACF73", text: "综" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { key: "pending", color: "#7FCFD8", text: "税" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#8083A3", text: "预" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#CFB673", text: "金" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#8083A3", text: "预" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#8083A3", text: "预" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#8083A3", text: "预" }
              },
              {
                taskId: "1709192275122",
                flowName: "集团年度预算（一上）",
                opTime: timer("2024-02-29 15:37:55"),
                taskStatus: "pending",
                opinion: "任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述任务 1 的描述",
                status: { color: "#8083A3", text: "预" }
              }
            ]),
          1000
        )
      );
      // 真实数据
      /* const param = {
        userName: "9999",
        userId: "9999",
        timestamp: 1717405554620,
        bizParam: {
          isPaging: 1,
          endTime: "2024-06-11 23:59:59",
          startTime: "2023-12-16 00:00:00",
          filterLastTask: "1",
          loadStartTask: "0",
          pageNo: 0,
          pageSize: 100,
          taskType: "pending"
        }
      };
      await GetTodoList(param).then((res: any) => {
        if (res.data && res.data.length) {
          res.data.map((item: any) => {
            item.opTime = timer(item.opTime);
            item.status = { color: "#CFB673", text: "金" };
          });
        }
        setListData(res.data);
        filterData(res.data, "待办");
        /!* if (res.data?.taskList && res.data.taskList.length) {
          res.data.taskList.map((item: any) => {
            item.opTime = timer(item.opTime);
            item.status = { color: "#CFB673", text: "金" };
          });
        }
        setListData(res.data.taskList);
        filterData(res.data.taskList, "待办");*!/
      });*/

      setListData(response);
      filterData(response, "待办");
    };

    fetchData();
  }, []);

  // 时间修改
  function timer(time: string) {
    return time.split(" ")[0];
  }

  const handleTabChange = (value: string) => {
    filterData(listData, value);
  };

  // tab: string
  const filterData = (data: any[], tab: string) => {
    let filtered;
    if (tab === "待办") {
      filtered = data.filter(task => task.taskStatus === "pending");
    } else if (tab === "已办") {
      filtered = [];
    } else {
      filtered = [];
    }
    setFilteredData(filtered);
  };

  // 将数据按每页 itemsPerPage 条分页
  const paginateData = (data: any[], itemsPerPage: number) => {
    const pages = [];
    for (let i = 0; i < data.length; i += itemsPerPage) {
      pages.push(data.slice(i, i + itemsPerPage));
    }
    return pages;
  };

  const menuItems = [
    {
      key: "1",
      label: "4 X 2",
      isDefalut: sizeType.pageSize == 5,
      action: () => changeType(1)
    },
    {
      key: "2",
      label: "4 X 4",
      isDefalut: sizeType.pageSize == 10,
      action: () => {
        changeType(2);
      }
    }
  ];
  function changeType(type: number) {
    if (type == 1) {
      setsizeType({ hights: "206px ", pageSize: 4 });
    } else if (type == 2) {
      setsizeType({ hights: "436px", pageSize: 10 });
    }
    message.success(`修改为 ${type == 1 ? "4 x 2 模式" : "4 x 4 模式"}`);
  }

  const goTaskCenter = () => {
    navigate("/feat/tabs");
    // navigate("/task_center");
  };

  return (
    <div className="task-list">
      <RightClickMenu menuItems={menuItems}>
        <Card
          style={{ height: sizeType.hights, width: "436px", backgroundColor: "rgba(255, 255, 255, 0.5)" }}
          styles={{
            header: { backgroundColor: "rgba(99, 176, 255, 0.9)", color: "#fff", padding: "0px 5px", minHeight: "46px" },
            body: { height: "calc(100% - 46px)", padding: 0 }
          }}
          hoverable
          bordered={false}
          title={
            <div style={{ display: "flex", alignItems: "center" }}>
              <div style={{ marginRight: 10 }}>
                <Hexagon backgroundColor="#fff" imageUrl={dbTitleInco} />
              </div>

              <span style={{ marginRight: 10, fontWeight: 400 }}>待办事项</span>
              <SegmentedList
                tabList={["待办", "已办", "已办结"]}
                activeColor="#7EBEFF"
                inactiveColor="#fff"
                onChange={handleTabChange}
              />
            </div>
          }
          extra={
            <Button type="link" style={{ color: "#fff", padding: "0px" }} onClick={goTaskCenter}>
              <span style={{ fontWeight: 500, marginRight: "-8px" }}>更多</span>
              <img src={leftInco} alt="" style={{ color: "#fff" }} />
            </Button>
          }
        >
          <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
            <Kcarousel listData={paginateData(filteredData, sizeType.pageSize)}>
              {item => (
                // 确保传递的是一个函数
                <TaskItem
                  id={item.taskId}
                  title={item.flowName}
                  date={item.opTime}
                  description={item.opinion}
                  status={item.status}
                />
              )}
            </Kcarousel>
          </div>
        </Card>
      </RightClickMenu>
    </div>
  );
};

export default TaskList;
